<template>
  <div class="department-management">
    <!-- 页面标题 -->
    <h2 class="page-title">科室管理</h2>
    <!-- 查询条件区 -->
    <div class="query-section">
      <el-form :inline="true" :model="queryParams" class="query-form">
        <el-form-item label="一级科室">
          <el-select v-model="queryParams.level1" placeholder="全部" clearable>
            <el-option
                v-for="item in level1Departments"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二级科室">
          <el-input
              v-model="queryParams.level2"
              placeholder="请输入二级科室名称"
              clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 科室列表 -->
    <div class="department-list">
      <el-table :data="departmentData" border style="width: 100%">
        <el-table-column   prop="level1" label="一级科室" width="180" />
        <el-table-column  prop="level2" label="二级科室" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
            >
              编辑二级科室
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑二级科室"
        width="50%"
        @close="handleCloseDialog"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="一级科室">
          <el-input v-model="editForm.level1" disabled />
        </el-form-item>
        <el-form-item label="二级科室">
          <el-select
              v-model="editForm.level2"
              multiple
              filterable
              allow-create
              placeholder="请选择或输入二级科室"
              style="width: 100%"
          >
            <el-option
                v-for="item in allLevel2Departments"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from "axios";
import {router} from "@/router/index.js";
// 一级科室数据
const level1Departments = ref([])

const getlevel1Departments=()=>{
  axios.get("/department/getDartment").then(res=>{
    level1Departments.value = res.data.obj
  })
}
// 科室列表数据
const departmentData = ref([])
const getDepartmentList=()=>{
  axios.get("/department/getDartmentByLevel").then(res=>{
    // 处理返回数据，确保数据结构正确
    departmentData.value = res.data.obj.map(item => ({
      level1: item.level1,
      level2: item.level2,
      level1Id: item.level1Id,
      level2Departments: item.level2Departments
    })
    )
  })
}
// 所有二级科室选项
const allLevel2Departments = ref([])
const getAllLevel2Departments=()=>{
  axios.get("/department/getAllLevel2Departments").then(res=>{
    allLevel2Departments.value = res.data.obj
  })
}
// 编辑对话框相关
const editDialogVisible = ref(false)
const editForm = reactive({
  id: null,
  level1: '',
  level2: []
})
// 查询参数
const queryParams = ref({
  level1: '',
  level2: ''
})
// 查询处理
const handleQuery = () => {
  const params = {
    level1: queryParams.level1,
    level2: queryParams.level2
  }
 axios.post("/department/searchDepartment",{params: params}).then(res=>{
   departmentData.value = res.data.obj.map(item => ({
     level1: item.level1,
     level2: item.level2,
     level1Id: item.level1Id,
     level2Departments: item.level2Departments
   }))
   getDepartmentList();
   ElMessage.success('查询成功');
 })
}

// 重置查询
const resetQuery = () => {
  queryParams.level1 = ''
  queryParams.level2 = ''
  handleQuery()
}

// 编辑科室
const handleEdit = (row) => {
  editForm.id = row.id
  editForm.level1 = row.level1
  editForm.level2 = row.level2.split('、')
  editDialogVisible.value = true
}

// 提交编辑
// 提交编辑
const handleSubmitEdit = async () => {
  try {
    // 1. 准备请求参数
    const params = {
      level1Id: editForm.id,  // 一级科室ID
      level2Names: editForm.level2
          .filter(name => name.trim()) // 过滤空值
          .map(name => name.trim())    // 去除前后空格
    };

 //   2. 验证数据
    if (!params.level1Id) {
      ElMessage.warning('请选择一级科室');
      return;
    }

    if (params.level2Names.length === 0) {
      ElMessage.warning('至少需要添加一个二级科室');
      return;
    }

    // 3. 调用API保存
    const response = await axios.post("/department/updateDepartment", params);

    if (response.data.code === 200) {
      // 4. 更新本地数据
      const index = departmentData.value.findIndex(item => item.level1Id === editForm.id);
      if (index !== -1) {
        departmentData.value[index].level2 = params.level2Names.join('、');
      }

      // 5. 关闭对话框并提示
      editDialogVisible.value = false;
      ElMessage.success('修改成功');

      // 6. 可选：刷新列表数据
      getDepartmentList();
    } else {
      ElMessage.error(response.data.message || '修改失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('修改失败: ' + (error.response?.data?.message || error.message));
  }
};
// 关闭对话框
const handleCloseDialog = () => {
  editForm.id = null
  editForm.level1 = ''
  editForm.level2 = []
}

onMounted(() => {
  getlevel1Departments();
      getDepartmentList();
  getAllLevel2Departments()
})
</script>

<style scoped>
.department-management {
  padding: 20px;
  background-color: #fff;
}

.breadcrumb {
  margin-bottom: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 20px;
  color: #333;
}

.query-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.department-list {
  margin-top: 20px;
}

.el-table {
  margin-top: 20px;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}
</style>